package com.github.dengmin.mysql.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.util.TimeZone;

/**
 * @Author dengmin
 * @Created 2020/8/14 上午10:51
 */
public class Jackson {
    private static final long serialVersionUID = 1L;

    private static final TimeZone timezone =TimeZone.getTimeZone("GMT+8");

    public static String toJsonString(Object object){
        return toJsonString(object, false);
    }

    public static String toJsonString(Object object, boolean prettyFormat){
        if(object == null) return null;
        ObjectMapper objectMapper = new ObjectMapper();
        try{
            objectMapper.configure(SerializationFeature.INDENT_OUTPUT, prettyFormat);
            objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
            objectMapper.setTimeZone(timezone);
            return objectMapper.writeValueAsString(object);
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return null;
    }

    public static String toJsonStringNonNull(Object object){
        return toJsonStringNonNull(object, false);
    }

    public static String toJsonStringNonNull(Object object, boolean prettyFormat){
        if(object == null) return null;
        ObjectMapper objectMapper = new ObjectMapper();
        try{
            objectMapper.configure(SerializationFeature.INDENT_OUTPUT, prettyFormat);
            objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            objectMapper.setTimeZone(timezone);
            return objectMapper.writeValueAsString(object);
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return null;
    }

}
